package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
            // 判断存储桶是否已经存在
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            //如果存储桶不存在，先创建一个存储桶，并赋权：只允许自己上传，允许所有人查看
            if (!bucketExists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
                //设置存储桶的访问权限
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().
                        bucket(minioProperties.getBucketName()).
                        config(createBucketPolicyConfig(minioProperties.getBucketName())).
                        build());
            }
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String uploadFileName = UUID.randomUUID().toString().replace("-", "") + "-" + originalFilename;
            String filename = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + uploadFileName;
            log.info("原始的文件名是:"+originalFilename);
            log.info("上传后的文件名是："+uploadFileName);
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(filename)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());

            return String.join("/", minioProperties.getEndpoint(), minioProperties.getBucketName(), filename);

    }


    /**
     * @param bucketName
     * @Desceription: 给存储桶赋权
     * @Return: java.lang.String
     * @Author: yangchengbao
     * @Date: 2024-12-10 15:12:23
     */
    private String createBucketPolicyConfig(String bucketName) {

        return """
                {
                  "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                  } ],
                  "Version" : "2012-10-17"
                }
                """.formatted(bucketName);
    }
}
